package com.lbt.weixin.server.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;

import com.lbt.framework.exception.MyException;
import com.lbt.weixin.common.bean.entity.User;
import com.lbt.weixin.common.service.UserService;
import com.lbt.weixin.server.common.CommonConfig;
import com.lbt.weixin.server.common.DateUtil;
import com.lbt.weixin.server.common.WeixinAppConfig;

/**
 * 登录授权
 * @author Moyq5
 * @date 2016年9月19日
 */
@Controller
@RequestMapping("/auth")
public class AuthController {
	
	private static Logger log = LoggerFactory.getLogger(AuthController.class);
	
	@Resource
	UserService userService;
	
	@RequestMapping("/login")
	public String login(String redirectUri, HttpServletRequest request) {
		log.debug("登录检查: redirectUri={}", redirectUri);
		WeixinAppConfig config = WeixinAppConfig.getInstance();
		String authPath = CommonConfig.getInstance().getThisDomain();
		try {
			authPath = authPath + "/auth/code?redirectUri=" + URLEncoder.encode(redirectUri, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String loginPage = SnsAPI.connectOauth2Authorize(config.getAppId(), authPath, true, "");
		return "redirect:" + loginPage;
	}
	
	
	@RequestMapping(value="/code", params = "!code")
	@ResponseBody
	public String code(String redirectUri) {
		log.debug("用户未授权公众号");
		return "redirect:" + redirectUri;
	}

	@RequestMapping(value="/code",params = "code")
	public String code(String code, String redirectUri, Model model, HttpServletRequest request) {
		log.debug("用户授权公众号");
		User user;
		try {
			user = addUser(code);
		} catch (MyException e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "fail";
		}
		
		request.getSession().setAttribute("userId", user.getUserId());
		
		return "redirect:" + redirectUri;

	}
	
	private User addUser(String code) throws MyException {
		WeixinAppConfig config = WeixinAppConfig.getInstance();
		SnsToken apiResult = SnsAPI.oauth2AccessToken(config.getAppId(), config.getAppSecret(), code);
		if (null != apiResult.getErrcode()) {
			throw new MyException(apiResult.getErrcode() + ":" + apiResult.getErrmsg());
		}
		return addUser(apiResult);
	}
	
	private User addUser(SnsToken token) throws MyException {
		weixin.popular.bean.user.User apiResult = SnsAPI.userinfo(token.getAccess_token(), token.getOpenid(), "zh_CN");
		if (null != apiResult.getErrcode()) {
			throw new MyException(apiResult.getErrcode() + ":" + apiResult.getErrmsg());
		}
		return addUser(apiResult);
	}
	
	private User addUser(weixin.popular.bean.user.User apiUser) {
		User user = new User();
		user.setOpenId(apiUser.getOpenid());
		List<User> userList = userService.list(user);
		if (userList.size() > 0) {
			user = userList.get(0);
		} else {
			user.setAddTime(DateUtil.getTimeStamp());
			user.setSubscribeTime(null == apiUser.getSubscribe_time() ? 0 : (apiUser.getSubscribe_time() * 1000L));
		}
		user.setCity(apiUser.getCity());
		user.setHeadUrl(apiUser.getHeadimgurl());
		user.setNickname(apiUser.getNickname());
		user.setProvince(apiUser.getProvince());
		user.setRemark(apiUser.getRemark());
		user.setSex(apiUser.getSex());
		user.setIsSubscribe((null != apiUser.getSubscribe() && apiUser.getSubscribe() == 1) ? true : false);
		try {
			if (null == user.getUserId()) {
				userService.persist(user);
			} else {
				userService.merge(user);
			}
		} catch (Exception e) {
			user.setNickname("特殊字符");
			if (null == user.getUserId()) {
				userService.persist(user);
			} else {
				userService.merge(user);
			}
		}
		
		return user;
	}

	
}
